import { createRouter, createWebHashHistory } from "vue-router";
import { userStore } from "@/stores/user";
import { useLayoutStore } from "@/stores/layout";

const router = createRouter({
	history: createWebHashHistory(import.meta.env.BASE_URL),
	routes: [
		{
			path: "",
			name: "Layout",
			component: () => import("@/layout/index.vue"),
			redirect: "/home",
		},
		// 登录
		{
			path: "/login",
			name: "Login",
			component: () => import("@/views/login/index.vue"),
		},
		// 404
		{
			path: "/:catchAll(.*)",
			name: "404",
			component: () => import("@/views/error-page/404.vue"),
		},
	],
});

router.beforeEach((to, from, next) => {
	const token = localStorage.getItem("token");
	const user = userStore();

	// 判断是否前往登录页, 如果已经登录了则返回来源页, 如果没登录则直接放行.
	if (to.name === "Login") return user.isLogin ? next(from.fullPath) : next();

	// 如果已经登录了则直接放过
	if (user.isLogin) return next();
	// 如果没Tokne则直接跳转到登录
	if (!token) return next({ name: "Login" });
	// 剩下的就是有Token
	Promise.all([userStore().getUserPermissions(), userStore().getUserInfo()])
		.catch(() => {})
		.then(() => {
			next(to.fullPath);
			useLayoutStore().addTags({ index: to.fullPath });
		});
});

export default router;
